﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows;
using NurseStation.DataModels;
using System.Windows.Data;

namespace NurseStation.common
{
    public class NursingRecordDataGridBehavior : Behavior<DataGrid>
    {
       
        /// <summary>
        ///  当前编辑的数据
        /// </summary>
        private NurseDayWork EditObj = new NurseDayWork();

     
        public NursingRecordDataGridBehavior()
        {
        }
    
        /// <summary>
        /// 当前记录  
        /// </summary>
        public NurseDayWork CurrVitSign
        {
            get { return (NurseDayWork)GetValue(CurrVitSignProperty); }
            set { SetValue(CurrVitSignProperty, value); }
        }
        public static readonly DependencyProperty CurrVitSignProperty =
            DependencyProperty.Register("CurrVitSign", typeof(NurseDayWork), typeof(NursingRecordDataGridBehavior), new PropertyMetadata(null));


        /// <summary>
        /// 单元格编辑事件
        /// </summary>
        public Action<dynamic> CellEditing
        {
            get { return (Action<dynamic>)GetValue(CellEditingProperty); }
            set { SetValue(CellEditingProperty, value); }
        }
        public static readonly DependencyProperty CellEditingProperty =   DependencyProperty.Register("CellEditing", typeof(Action<dynamic>), typeof(NursingRecordDataGridBehavior), new PropertyMetadata(null));


        #region override
        protected override void OnAttached()
        {
            AssociatedObject.BeginningEdit += BeginningEdit;
            AssociatedObject.CurrentCellChanged += AssociatedObject_CurrentCellChanged;
            AssociatedObject.CellEditEnding += EndingCellEdit;
            AssociatedObject.PreviewKeyDown += AssociatedObject_PreviewKeyDown;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.BeginningEdit -= BeginningEdit;
            AssociatedObject.CurrentCellChanged -= AssociatedObject_CurrentCellChanged;
            AssociatedObject.CellEditEnding -= EndingCellEdit;
            AssociatedObject.PreviewKeyDown -= AssociatedObject_PreviewKeyDown;
        }
        #endregion


        /// <summary>
        /// 单元格编辑前逻辑处理-记录  2023-05-24
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            if (CurrVitSign == null || CurrVitSign.IS_SUM==1)
            {
                e.Cancel = true;
                return;
            }
            EditObj = new NurseDayWork() { ID = CurrVitSign.ID };
            if (e.Column.GetType() == typeof(DataGridTextColumn))
            {
                EditObj.CurEditCol = ((DataGridTextColumn)e.Column).SortMemberPath;
                string res = TriageEx.FindProValue<string>(EditObj.CurEditCol, CurrVitSign);
                EditObj.BeforeText = res;
            }
            else if (e.Column.GetType() == typeof(DataGridTemplateColumn))
            {
                #region 模板列找修改的列名
                try
                {
                    DataGridTemplateColumn templeColumn = (DataGridTemplateColumn)e.Column;
                    FrameworkElement element = templeColumn.GetCellContent(e.Row);
                    object element2 = templeColumn.CellTemplate.FindName("DropTempText", element);
                    if (element2 != null && element2.GetType() == typeof(TextBlock))
                    {
                        TextBlock tb = (TextBlock)element2;
                        System.Windows.Data.BindingExpression kl = tb.GetBindingExpression(TextBlock.TextProperty);
                        Binding hhh = kl.ParentBinding;
                        EditObj.CurEditCol = hhh.Path.Path;
                        EditObj.BeforeText = tb.Text;
                    }
                    else
                    {
                        EditObj.ID = 0;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.GetLogHelper().Error("BeginEdit模板列报错：" + ex);
                }
                #endregion
            }
        }


        /// <summary>
        /// 单元格编辑后逻辑处理-保存  2023-05-24
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EndingCellEdit(object sender, DataGridCellEditEndingEventArgs e)
        {
            try
            {
                if (e.Column == null || EditObj == null || sender == null || EditObj.IS_SUM==1)
                    return;
                TextBox box = null;
                string EndText = "";
                if (e.Column is DataGridTextColumn)
                {
                    box = (e.EditingElement as TextBox);
                    if (box != null)
                        EndText = box.Text.ToString();
                }
                else if (e.Column is DataGridTemplateColumn)
                {
                    box = MyVisualTreeHelper.FindVisualChild<TextBox>(e.EditingElement);
                    if (box != null)
                        EndText = box.Text.ToString();
                }
                if (!string.IsNullOrEmpty(EndText))
                {
                    int a = 0;
                    if (!int.TryParse(EndText, out a))
                    {
                        MessageBox.Show("录入的不是数字");
                        //notifiaction.AddNotifiaction(new NotifiactionModel() { Title = "提示", Content = "录入的不是数字！", NotifiactionType = EnumPromptType.Error });
                        if (box != null)
                        {
                            box.Text = EditObj.BeforeText;
                        }
                        return;
                    }
                }
                if (EditObj.BeforeText == EndText)
                {
                    return;
                }
                TriageEx.FindProSetValue(EditObj.CurEditCol, EndText, EditObj);
                dynamic obj = new ExpandoObject();
                obj.Command = "Save";
                obj.Data = EditObj;
                CellEditing(obj);
                EditObj = new NurseDayWork() { };
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error("整体录入报错" + ex);
            }
        }


        /// <summary>
        /// 选中的单元格改变  2023-05-24
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AssociatedObject_CurrentCellChanged(object sender, System.EventArgs e)
        {
            try
            {
                var item = AssociatedObject.CurrentCell;
                if (AssociatedObject.CurrentItem != null && AssociatedObject.CurrentItem is NurseDayWork)
                {
                    CurrVitSign = (NurseDayWork)AssociatedObject.CurrentItem;
                }
                if (item != null)
                {
                    AssociatedObject.BeginEdit();
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
                return;
            }
        }

        /// <summary>
        /// 按键触发事件  2023-05-24
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AssociatedObject_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            try
            {
                var uie = e.OriginalSource as System.Windows.UIElement;
                switch (e.Key)
                {
                    case Key.Enter:
                        NextCellEdit();
                        break;
                    //case Key.Down:
                    //    CellEditByXY(0, 1);
                    //    break;
                    //case Key.Up:
                    //    CellEditByXY(0, -1);
                    //    break;
                    case Key.Left:
                        CellEditByXY(-1, 0);
                        break;
                    case Key.Right:
                        if (uie is TextBox tb2)
                        {
                            if (tb2.Name == "SSY")
                            {
                                TextBox TbSZY = MyVisualTreeHelper.GetVisualBrother<TextBox>(tb2)?.Find(c => c.Name == "SZY");
                                TbSZY?.Focus();
                            }
                            else
                            {
                                CellEditByXY(1, 0);
                            }
                        }
                        else
                        {
                            CellEditByXY(1, 0);
                        }
                        break;
                    default:
                        return;
                }
                e.Handled = true;
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error("按键处理事件报错" + ex);
            }
        }


        #region 自定义事件
 
        /// <summary>
        /// 跳转编辑下一个单元格  2023-05-24
        /// </summary>
        private void NextCellEdit()
        {
            CellEditByXY(0, 1);
        }

        /// <summary>
        /// 通过上下左右移动选中单元，换行或换列处理  2023-05-24
        /// </summary>
        /// <param name="x">右偏移</param>
        /// <param name="y">下偏移</param>
        private void CellEditByXY(int x = 0, int y = 0)
        {
            int canEditCol = 4;
            if (x != 0 && y != 0)
            {
                return;
            }

            Int32 row = this.AssociatedObject.Items.IndexOf(this.AssociatedObject.CurrentItem);
            Int32 Col = this.AssociatedObject.Columns.IndexOf(this.AssociatedObject.CurrentColumn);
            if (x > 0)
            {//右
                if (Col >= this.AssociatedObject.Columns.Count - 1)
                {
                    row += 1;
                    Col = canEditCol;
                }
                else
                {
                    Col += 1;
                }
            }
            if (x < 0)
            {//左
                if (Col == canEditCol)
                {
                    row -= 1;
                    Col = this.AssociatedObject.Columns.Count - 1;
                }
                else
                {
                    Col -= 1;
                }
            }
            if (y > 0)
            {//下
                if (row >= this.AssociatedObject.Items.Count - 1)
                {
                    row = 0;
                    Col = Col + 1;
                }
                else
                {
                    row += 1;
                }
            }
            if (y < 0)
            {//上
                if (row == 0)
                {
                    row = this.AssociatedObject.Items.Count - 1;
                    Col = Col - 1;
                    if (Col < canEditCol)
                    {
                        return;
                    }
                }
                else
                {
                    row -= 1;
                }
            }
            var Nextcell = MyVisualTreeHelper.GetCell(this.AssociatedObject, row, Col);
            if (Nextcell != null)
            {
                Nextcell.Focus();
                this.AssociatedObject.BeginEdit();
            }
        }


        #endregion

      
    }
}
